﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FPSInput : MonoBehaviour
{

    public float speed = 6.0f;
    public const float baseSpeed = 6.0f;
    //引用CharacterControler的变量
    private CharacterController _character;

    public float gravity = -9.8f;

    void Awake()
    {
        Messenger<float>.AddListener(GameEvent.SPEED_CHANGED, OnSpeedChanged);
    }

    void OnDestroy()
    {
        Messenger<float>.RemoveListener(GameEvent.SPEED_CHANGED, OnSpeedChanged);
    }

    // Use this for initialization
    void Start()
    {
        _character = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        float deltaX = Input.GetAxis("Horizontal") * speed;
        float deltaZ = Input.GetAxis("Vertical") * speed;
        //transform.Translate(deltaX * Time.deltaTime, 0, deltaZ * Time.deltaTime);

        Vector3 movement = new Vector3(deltaX, 0, deltaZ);
        //将对角移动的速度限制为何沿着轴移动的速度一样
        movement = Vector3.ClampMagnitude(movement, speed);
        //使用重力值时而不只是0
        movement.y = gravity;

        movement *= Time.deltaTime;
        //把movement向量从本地变换为全局坐标
        movement = transform.TransformDirection(movement);
        //告知CharacterController通过movement向量移动
        _character.Move(movement);
    }

    private void OnSpeedChanged(float value)
    {
        speed = baseSpeed * value;
    }
}